import { gp } from '@vui'
import isEmpty from 'lodash/isEmpty'
import cloneDeep from 'lodash/cloneDeep'
import trim from 'lodash/trim'
import { translateTitle } from '@/utils/i18n'
//必须带done回调 执行完成调用
export default function updateTableData({ vm, action, done, eventName, callbackData }) {
  const tableId = action.extension.tableId.value && action.extension.tableId.value[0]
  const matchField = action.extension.matchField.value
  const updateField = action.extension.updateField.value

  if (tableId && matchField) {
    let _tableSelf = vm.vuiComponents[tableId].self
    let _value = cloneDeep(_tableSelf.info.data.requestData.data)
    let changeVal = null
    let tableValueList = []
    if (!isEmpty(_value)) {
      _value.forEach((item) => {
        if (callbackData[matchField] === item[matchField]) {
          // 更新对应字段
          if (updateField) {
            updateField.split(',').forEach((fieldItem) => {
              item[trim(fieldItem)] = callbackData[trim(fieldItem)]
            })
            tableValueList.push(item)
          } else {
            // 无更新字段则更新所有数据
            changeVal = item
          }
        } else {
          tableValueList.push(item)
        }
      })
    }
    if (changeVal) {
      tableValueList.push(callbackData)
    }
    _tableSelf.info.data.requestData.data = tableValueList
    done(null, {})
  } else {
    gp.$baseMessage(`${translateTitle('Ve.eventTask.没有找到组件或没有匹配字段') - 1002}`, 'warning')
    // 修改任务队列执行状态，防止下一次事件被拦截
    vm[`${eventName}IsRunning`] = false
    done(null, {})
  }
}
